#!/usr/local/bin/python
# -*- coding: utf-8 -*-

import os
from datetime import datetime

from PyQt5.QtGui import QBrush, QColor
from dateutil.relativedelta import relativedelta


from PyQt5.QtWidgets import QWidget, QAbstractItemView, QTableWidgetItem, QMessageBox, QFileDialog
from PyQt5 import QtWidgets
from xToolkit.xstring import xstring

import init
import initAlipayPage
import toolkit
import ParseAliPay
from AutoParseBill import AutoParseBill
from BillParseDialog import BillParseDialog
from ParseAliPayNew import ParseAlipayNew
from data_alchemy.account_voucher_alchemy import AccountVoucherAlchemy
from data_alchemy.alipay_bill_new_alchemy import AlipayBillNewAlchemy

from data_alchemy.alipay_voucher_alchemy import AlipayVoucherAlchemy
from data_alchemy.alipay_voucher_preview_alchemy import AlipayVoucherPreviewAlchemy
from data_alchemy.investment_flow_alchemy import InvestmentFlowAlchemy
from initLogger import logger
from data_alchemy.alipay_bill_aclchemy import AlipayBillAlchemy
from initXirrPage import FLOW_TYPE_DING_TOU
#from ui.AlipayBillUI import Ui_AlipayBill
from ui.AlipayBillUI_relative_layout import Ui_AlipayBill


class AlipayBillWidget(QWidget, Ui_AlipayBill):
    def __init__(self):
        super(AlipayBillWidget, self).__init__()

        self.currentDate = datetime.now()  #记录当前事件
        self.targetDate = self.currentDate  - relativedelta(days=init.GO_DAYS)#记录当前系统查看数据的时间


        self.setupUi(self)

        self.initAlipayBill()
        #self.initAccountVoucherUI()


    def initAlipayBill(self):
        '''
        函数功能：初始化支付宝页面
        :return:
        '''
        logger.debug("call initAlipayBill function")
        self.initAlipayBillUI()



        #新支付宝账单展示
        self.initAlipayBillNewTableUI()
        self.initAlipayBillNewTableData()

        #初始化支付宝账单表格
        #self.initAlipayBillTableUI()
        #self.initAlipayBillTableData()

        #初始化支付宝记账凭证预览表格
        self.initAlipayVoucherPreviewTableUI()
        self.initAlipayVoucherPreviewTableData()

        #初始化支付宝记账凭证表格
        self.initAlipayVoucherTableUI()
        self.initAlipayVoucherTableData()

        self.tabWidget.setCurrentIndex(1)

    def initAlipayBillTitleUI(self):
        accountBookTitleStr="%d年%d月支付宝账单"%(self.targetDate.year, self.targetDate.month)
        self.title_label.setText(accountBookTitleStr)

    def initAlipayBillUI(self):
        self.initAlipayBillTitleUI()

        #初始化查询模块相关控件
        self.year_comboBox.addItems(init.YEAR_NAME_LIST)
        self.month_comboBox.addItems(init.MONTH_NAME_LIST)
        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))

    def initAlipayBillImportBox(self):
        '''
        作废不再使用
        函数功能；初始化数据导入栏部分内容
        :return:
        '''
        logger.debug("call initAlipayBillImportBox function")
        self.year_comboBox.addItems(init.YEAR_NAME_LIST)
        self.month_comboBox.addItems(init.MONTH_NAME_LIST)
        #result = self.targetDate.year-init.FIRST_YEAR
        self.year_comboBox.setCurrentIndex(self.targetDate.year-init.FIRST_YEAR)
        self.month_comboBox.setCurrentIndex(self.targetDate.month-1)

    def initAlipayBillTableUI(self):
        '''
        函数功能：初始化支付宝账单页面UI
        :return:
        '''
        logger.debug("call initAlipayBillTableUI function")

        self.alipay_bill_tableWidget.setRowCount(initAlipayPage.ALIPAY_BILL_ROW_COUNT)  # 设置行数目
        self.alipay_bill_tableWidget.setColumnCount(initAlipayPage.ALIPAY_BILL_COLUMN_COUNT)  # 设置列数目
        self.alipay_bill_tableWidget.setHorizontalHeaderLabels(initAlipayPage.ALIPAY_BILL_COLUMN_CONTEXT)

        self.alipay_bill_tableWidget.resizeRowsToContents()  # 设置行宽自适应
        # self.alipay_bill_tableWidget.resizeColumnsToContents()  # 设置列宽自适应
        self.alipay_bill_tableWidget.setShowGrid(True)  # 设置显示网络线
        self.alipay_bill_tableWidget.setAlternatingRowColors(True)  # 设置表格颜色交错显示
        self.alipay_bill_tableWidget.verticalHeader().setVisible(False)  # 隐藏垂直标题
        self.alipay_bill_tableWidget.horizontalHeader().setStretchLastSection(True)  # 设置最后一列自动填充容

        self.alipay_bill_tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置选中整行
        self.alipay_bill_tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)  # 禁止编辑单元格

        self.alipay_bill_tableWidget.setColumnWidth(0, 80)
        self.alipay_bill_tableWidget.setColumnWidth(1, 80)
        self.alipay_bill_tableWidget.setColumnWidth(2, 300)
        self.alipay_bill_tableWidget.setColumnWidth(3, 150)
        self.alipay_bill_tableWidget.setColumnWidth(4, 300)
        self.alipay_bill_tableWidget.setColumnWidth(5, 200)
        self.alipay_bill_tableWidget.setColumnWidth(6, 100)
        self.alipay_bill_tableWidget.setColumnWidth(7, 100)
        self.alipay_bill_tableWidget.setColumnWidth(8, 100)
        self.alipay_bill_tableWidget.setColumnWidth(9, 200)
        self.alipay_bill_tableWidget.setColumnWidth(10, 200)
        self.alipay_bill_tableWidget.setColumnWidth(11, 200)

    def initAlipayBillTableData(self):
        '''
        函数功能：初始化支付宝账单表格数据
        :return:
        '''
        logger.debug("call initAliypayBillTableData function")
        #self.showAlipayBillData()
        self.showAlipayBillDataByType(initAlipayPage.ALL_BILL_RADIO_TYPE)


    def initAlipayVoucherPreviewTableUI(self):
        '''
        函数功能：初始化支付宝记账凭证预览表格UI
        :return:
        '''
        logger.debug("call showAlipayVoucherPreview function")

        self.alipay_voucher_preview_tableWidget.setRowCount(initAlipayPage.ALIPAY_VOUCHER_PREVIEW_ROW_COUNT)  # 设置行数目
        self.alipay_voucher_preview_tableWidget.setColumnCount(initAlipayPage.ALIPAY_VOUCHER_PREVIEW_COLUMN_COUNT)  # 设置列数目
        self.alipay_voucher_preview_tableWidget.setHorizontalHeaderLabels(initAlipayPage.ALIPAY_VOUCHER_PREVIEW_COLUMN_CONTEXT)

        self.alipay_voucher_preview_tableWidget.resizeRowsToContents()  # 设置行宽自适应
        #self.voucher_preview_tableWidget.resizeColumnsToContents()  # 设置列宽自适应
        self.alipay_voucher_preview_tableWidget.setShowGrid(True)  # 设置显示网络线
        self.alipay_voucher_preview_tableWidget.setAlternatingRowColors(True)  # 设置表格颜色交错显示
        self.alipay_voucher_preview_tableWidget.verticalHeader().setVisible(False)  # 隐藏垂直标题
        self.alipay_voucher_preview_tableWidget.horizontalHeader().setStretchLastSection(True)  # 设置最后一列自动填充容

        self.alipay_voucher_preview_tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置选中整行
        self.alipay_voucher_preview_tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)  # 禁止编辑单元格

        self.alipay_voucher_preview_tableWidget.setColumnWidth(0, 100)
        self.alipay_voucher_preview_tableWidget.setColumnWidth(1, 600)
        self.alipay_voucher_preview_tableWidget.setColumnWidth(2, 150)
        self.alipay_voucher_preview_tableWidget.setColumnWidth(3, 150)
        self.alipay_voucher_preview_tableWidget.setColumnWidth(4, 600)


    def initAlipayVoucherPreviewTableData(self):
        '''
        函数功能：初始化支付宝记账凭证预览表格数据
        :return:
        '''

        logger.debug("call initAlipayVoucherPreviewTableData function")
        self.showAlipayVoucherPreview()

    def showAlipayVoucherPreview(self):
        '''
        函数功能：展示支付宝记账凭证预览数据
        :return:
        '''
        logger.debug("call showAlipayVoucherPreview function")

        accountingVoucherPreview = AlipayVoucherPreviewAlchemy()
        startDateStr, endDateStr = toolkit.monthlyChange(self.targetDate.year, self.targetDate.month)
        alipayVoucherResult = accountingVoucherPreview.SearchVoucherByDate(startDateStr, endDateStr)

        alipayVoucherResultLen = len(alipayVoucherResult)


        self.alipay_voucher_preview_tableWidget.setRowCount(alipayVoucherResultLen+1)
        self.alipay_voucher_preview_tableWidget.clearContents()

        for i in range(alipayVoucherResultLen):
            #logger.debug("支付宝记账凭证展示第 %d 项数据 " % (i))
            dataRow = alipayVoucherResult[i]

            noStr = "%d\t" % (i+1)
            noItem = QTableWidgetItem(noStr)
            self.alipay_voucher_preview_tableWidget.setItem(i, 0, noItem)

            #摘要
            summaryItem = QTableWidgetItem(dataRow.summary)
            self.alipay_voucher_preview_tableWidget.setItem(i, 1, summaryItem)

            #日期
            accountDateStr = str(dataRow.account_date)
            accountDateItem = QTableWidgetItem(accountDateStr)
            self.alipay_voucher_preview_tableWidget.setItem(i, 2, accountDateItem)

            #金额
            if dataRow.property_increase_value != 0:
                moneyValue = dataRow.property_increase_value
            elif dataRow.property_decrease_value != 0:
                moneyValue = dataRow.property_decrease_value
            elif dataRow.ownership_increase_value !=0:
                moneyValue = dataRow.ownership_increase_value
            else :
                moneyValue = dataRow.ownership_decrease_value

            moneyValueStr=xstring.dispose(toolkit.processValueSignificant(moneyValue)).humanized_amount(complex=True)
            moneyValueWiggetItem = QTableWidgetItem(moneyValueStr)
            self.alipay_voucher_preview_tableWidget.setItem(i, 3, moneyValueWiggetItem)



            #详情
            detailContext=""
            if dataRow.property_increase_name != "":
                if detailContext!="":
                    detailContext = detailContext + "\n"
                detailContext = detailContext + "资产增加：%s"%(dataRow.property_increase_name)
            if dataRow.property_decrease_name !="":
                if detailContext!="":
                    detailContext = detailContext + "\n"
                detailContext = detailContext + "资产减少：%s" % (dataRow.property_decrease_name)
            if dataRow.ownership_increase_name != "":
                if detailContext!="":
                    detailContext = detailContext + "\n"
                detailContext = detailContext + "权属增加：%s" % (dataRow.ownership_increase_name)
            if dataRow.ownership_decrease_name != "":
                if detailContext!="":
                    detailContext = detailContext + "\n"
                detailContext = detailContext + "权属减少：%s" % (dataRow.ownership_decrease_name)

            #去掉结尾的"\n"

            detailContextWiggetItem = QTableWidgetItem(detailContext)
            self.alipay_voucher_preview_tableWidget.setItem(i, 4, detailContextWiggetItem)

        self.alipay_voucher_preview_tableWidget.resizeRowsToContents()  # 设置行宽自适应
        # self.alipay_voucher_preview_tableWidget.resizeColumnsToContents()  # 设置列宽自适应


    def initAlipayVoucherTableUI(self):
        '''
        函数功能：初始化支付宝记账凭证表格UI
        :return:
        '''
        logger.debug("call initAlipayVoucherTableUI function")

        self.alipay_voucher_tableWidget.setRowCount(initAlipayPage.ALIPAY_VOUCHER_PREVIEW_ROW_COUNT)  # 设置行数目
        self.alipay_voucher_tableWidget.setColumnCount(initAlipayPage.ALIPAY_VOUCHER_PREVIEW_COLUMN_COUNT)  # 设置列数目
        self.alipay_voucher_tableWidget.setHorizontalHeaderLabels(initAlipayPage.ALIPAY_VOUCHER_PREVIEW_COLUMN_CONTEXT)

        self.alipay_voucher_tableWidget.resizeRowsToContents()  # 设置行宽自适应
        # self.voucher_preview_tableWidget.resizeColumnsToContents()  # 设置列宽自适应
        self.alipay_voucher_tableWidget.setShowGrid(True)  # 设置显示网络线
        self.alipay_voucher_tableWidget.setAlternatingRowColors(True)  # 设置表格颜色交错显示
        self.alipay_voucher_tableWidget.verticalHeader().setVisible(False)  # 隐藏垂直标题
        self.alipay_voucher_tableWidget.horizontalHeader().setStretchLastSection(True)  # 设置最后一列自动填充容

        self.alipay_voucher_tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置选中整行
        self.alipay_voucher_tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)  # 禁止编辑单元格

        self.alipay_voucher_tableWidget.setColumnWidth(0, 100)
        self.alipay_voucher_tableWidget.setColumnWidth(1, 600)
        self.alipay_voucher_tableWidget.setColumnWidth(2, 150)
        self.alipay_voucher_tableWidget.setColumnWidth(3, 150)
        self.alipay_voucher_tableWidget.setColumnWidth(4, 600)

    def initAlipayVoucherTableData(self):
        '''
        函数功能；初始化支付宝记账凭证表格数据
        :return:
        '''
        logger.debug("call initAlipayVoucherTableData function")
        self.showAlipayVoucher()

    def showAlipayVoucher(self):
        '''
        函数功能；展示支付宝记账凭证数据
        :return:
        '''
        logger.debug("call showAlipayVoucher function")

        alipayVoucherAlchemy = AlipayVoucherAlchemy()
        startDateStr, endDateStr = toolkit.monthlyChange(self.targetDate.year, self.targetDate.month)
        alipayVoucherResult = alipayVoucherAlchemy.SearchVoucherByDate(startDateStr, endDateStr)

        alipayVoucherResultLen = len(alipayVoucherResult)

        self.alipay_voucher_tableWidget.setRowCount(alipayVoucherResultLen+1)
        self.alipay_voucher_tableWidget.clearContents()

        for i in range(alipayVoucherResultLen):
            #logger.debug("支付宝记账凭证展示第 %d 项数据 " % (i))
            dataRow = alipayVoucherResult[i]

            noStr = "%d\t" % (i+1)
            noItem = QTableWidgetItem(noStr)
            self.alipay_voucher_tableWidget.setItem(i, 0, noItem)

            #摘要
            summaryItem = QTableWidgetItem(dataRow.summary)
            self.alipay_voucher_tableWidget.setItem(i, 1, summaryItem)

            #日期
            accountDateStr = str(dataRow.account_date)
            accountDateItem = QTableWidgetItem(accountDateStr)
            self.alipay_voucher_tableWidget.setItem(i, 2, accountDateItem)

            #金额
            if dataRow.property_increase_value != 0:
                moneyValue = dataRow.property_increase_value
            elif dataRow.property_decrease_value != 0:
                moneyValue = dataRow.property_decrease_value
            elif dataRow.ownership_increase_value !=0:
                moneyValue = dataRow.ownership_increase_value
            else :
                moneyValue = dataRow.ownership_decrease_value

            moneyValueStr=xstring.dispose(toolkit.processValueSignificant(moneyValue)).humanized_amount(complex=True)
            moneyValueWiggetItem = QTableWidgetItem(moneyValueStr)
            self.alipay_voucher_tableWidget.setItem(i, 3, moneyValueWiggetItem)



            #详情
            detailContext=""
            if dataRow.property_increase_name != "":
                if detailContext!="":
                    detailContext = detailContext + "\n"
                detailContext = detailContext + "资产增加：%s"%(dataRow.property_increase_name)
            if dataRow.property_decrease_name !="":
                if detailContext!="":
                    detailContext = detailContext + "\n"
                detailContext = detailContext + "资产减少：%s" % (dataRow.property_decrease_name)
            if dataRow.ownership_increase_name != "":
                if detailContext!="":
                    detailContext = detailContext + "\n"
                detailContext = detailContext + "权属增加：%s" % (dataRow.ownership_increase_name)
            if dataRow.ownership_decrease_name != "":
                if detailContext!="":
                    detailContext = detailContext + "\n"
                detailContext = detailContext + "权属减少：%s" % (dataRow.ownership_decrease_name)

            #去掉结尾的"\n"

            detailContextWiggetItem = QTableWidgetItem(detailContext)
            self.alipay_voucher_tableWidget.setItem(i, 4, detailContextWiggetItem)

        self.alipay_voucher_tableWidget.resizeRowsToContents()  # 设置行宽自适应
        #self.alipay_voucher_tableWidget.resizeColumnsToContents()  # 设置列宽自适应

    def onSearch(self):
        '''
        函数功能：响应“查询”事件
        :return:
        '''

        logger.debug("call onSearch function")

        self.tabWidget.setCurrentIndex(1)

        #获取查询时间
        year = int(self.year_comboBox.currentText())
        month = int(self.month_comboBox.currentText())
        self.targetDate = toolkit.setTargetDate(year, month)

        self.initAlipayBillTitleUI()

        #self.initAlipayBillTableUI()
        #self.initAlipayBillTableData()

        #新支付宝账单展示
        self.initAlipayBillNewTableUI()
        self.initAlipayBillNewTableData()


        self.initAlipayVoucherPreviewTableUI()
        self.initAlipayVoucherPreviewTableData()

        # 初始化支付宝记账凭证表格
        self.initAlipayVoucherTableUI()
        self.initAlipayVoucherTableData()



    def onGoLastMonth(self):
        """
        函数功能；展示上一个月的账簿数据
        :return:
        """


        self.targetDate = toolkit.getLastMonth(self.targetDate, number=1)
        logger.debug("target year: %d   month: %d" % (self.targetDate.year, self.targetDate.month))
        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))

        self.initAlipayBillTitleUI()

        #self.initAlipayBillTableUI()
        #self.initAlipayBillTableData()

        self.initAlipayVoucherPreviewTableUI()
        self.initAlipayVoucherPreviewTableData()

        # 初始化支付宝记账凭证表格
        self.initAlipayVoucherTableUI()
        self.initAlipayVoucherTableData()

        self.initAlipayBillNewTableData()


    def onGoNextMonth(self):
        """
        函数功能；展示下一个月的账簿数据
        :return:
        """

        self.targetDate = toolkit.getNextMonth(self.targetDate, number=1)
        logger.debug("target year: %d   month: %d" % (self.targetDate.year, self.targetDate.month))

        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))

        self.initAlipayBillTitleUI()

        self.initAlipayBillNewTableUI()
        self.initAlipayBillNewTableData()



        self.initAlipayBillTableUI()
        self.initAlipayBillTableData()

        self.initAlipayVoucherPreviewTableUI()
        self.initAlipayVoucherPreviewTableData()

        # 初始化支付宝记账凭证表格
        self.initAlipayVoucherTableUI()
        self.initAlipayVoucherTableData()

        # 新支付宝账单展示
        self.initAlipayBillNewTableUI()
        self.initAlipayBillNewTableData()


    def onNewImportAlipayBill(self):
        '''
        函数功能：基于新的支付宝账单excel表进行导入
        :return:
        '''

        logger.debug("call onNewImportAlipayBill function")



        dir = QFileDialog()
        dir.setFileMode(QFileDialog.ExistingFile)
        dir.setDirectory(".//")
        dir.setNameFilter("Data File(*.xlsx *.xls)")
        if dir.exec_()!=True:
            #异常退出
            logger.debug("end  onImportAlipayBill  1 ")
            return False
        filePath = dir.selectedFiles()[0]
        logger.debug("select file:%s"%filePath)
        fileName = os.path.basename(filePath)  # 输出为 class1.py

        try:
            subFileNames = fileName.split(".")
            extFileName = subFileNames[1]

        except Exception:
            self.showErrorMessage("文件名格式，正确格式为：alipay_bill_2022_10.xlsx ")
            # 异常退出
            logger.debug("【错误】 文件名格式，正确格式为：alipay_bill_2022_10.xlsx ")
            return False


        if extFileName != "xlsx" and extFileName != "xls":
            logger.debug("【错误】 文件非 excel文件")
            self.showErrorMessage("【错误】 文件非 excel文件")
            return False

        parseAlipayNew=ParseAlipayNew()
        parseAlipayNew.loadAlipayBill(filePath)

        return True

    def onImportAlipayBill(self):
        '''
        函数功能：响应“支付宝账单导入”功能
        :return:
        '''

        logger.debug("call onImportAlipayBill function")



        dir = QFileDialog()        
        dir.setFileMode(QFileDialog.ExistingFile)
        dir.setDirectory(".//")
        dir.setNameFilter("Data File(*.xlsx *.xls)")
        if dir.exec_()!=True:
            #异常退出
            logger.debug("end  onImportAlipayBill  1 ")
            return False
        filePath = dir.selectedFiles()[0]
        logger.debug("select file:%s"%filePath)
        fileName = os.path.basename(filePath)  # 输出为 class1.py
        try:
            subFileNames = fileName.split(".")
            subStrs = subFileNames[0].split("_")
            extFileName = subFileNames[1]
            fileYear = int(subStrs[2])
            fileMonth = int(subStrs[3])
        except Exception:
            self.showErrorMessage("文件名格式，正确格式为：alipay_bill_2022_10.xlsx ")
            # 异常退出
            logger.debug("【错误】 文件名格式，正确格式为：alipay_bill_2022_10.xlsx ")
            return False

        if extFileName != "xlsx" and extFileName != "xls":
            logger.debug("【错误】 文件非 excel文件")
            self.showErrorMessage("【错误】 文件非 excel文件")
            return False


        if (fileYear!=self.targetDate.year or  fileMonth!=self.targetDate.month):
            #时间不对
            self.showErrorMessage("导入账单时间不一致")
            logger.debug("【错误】导入账单时间不一致")
            return False

        alipayBillAlchemy = AlipayBillAlchemy()
        alipayBillAlchemyResult = alipayBillAlchemy.SearchAlipayBillByMonth(self.targetDate.year, self.targetDate.month)

        if len(alipayBillAlchemyResult) > 0:
            #该月数据已经导入
            self.showErrorMessage("该月份支付宝账单已经导入")
            logger.debug("end  onImportAlipayBill  4 ")
            return False

        ParseAliPay.addAlipayBillByMonth(filePath, self.targetDate.year, self.targetDate.month)
        return True

    def onNewSelectBill(self):
        '''
        函数功能：在新账单上实现，实现特定条件筛选功能
        :return:
        '''

        self.initAlipayBillNewTableUI()
        if self.new_huabei_bill_radioButton.isChecked():
            logger.debug("new 展示花呗账单")
            self.showAlipayBillNewDataByType(initAlipayPage.HUA_BEI_BILL_RADIO_TYPE)
        elif self.new_cash_bill_radioButton.isChecked():
            logger.debug("new 展示现金账单")
            self.showAlipayBillNewDataByType(initAlipayPage.CASH_BILL_RADIO_TYPE)
        elif self.new_large_bill_radioButton.isChecked():
            logger.debug("new 展示大额账单")
            self.showAlipayBillNewDataByType(initAlipayPage.LARGE_BILL_RADIO_TYPE)
        elif self.new_unusual_bill_radioButton.isChecked():
            logger.debug("new 展示异常账单")
            self.showAlipayBillNewDataByType(initAlipayPage.UNUSUAL_BILL_RADIO_TYPE)
        elif self.new_invalid_bill_radioButton.isChecked():
            logger.debug("展示无效账单")
            self.showAlipayBillNewDataByType(initAlipayPage.INVALID_BILL_RADIO_TYPE)
        else:
            self.showAlipayBillNewDataByType(initAlipayPage.ALL_BILL_RADIO_TYPE)
            logger.debug("new 展示所有账单")


    def onSelectBill(self):
        '''
        函数功能：筛选支付宝账单
        :return:
        '''

        self.initAlipayBillTableUI()
        if self.huabei_bill_radioButton.isChecked():
            logger.debug("展示花呗账单")
            self.showAlipayBillDataByType(initAlipayPage.HUA_BEI_BILL_RADIO_TYPE)
        elif self.cash_bill_radioButton.isChecked():
            logger.debug("展示现金账单")
            self.showAlipayBillDataByType(initAlipayPage.CASH_BILL_RADIO_TYPE)
        elif self.large_bill_radioButton.isChecked():
            logger.debug("展示大额账单")
            self.showAlipayBillDataByType(initAlipayPage.LARGE_BILL_RADIO_TYPE)
        elif self.unusual_bill_radioButton.isChecked():
            logger.debug("展示异常账单")
            self.showAlipayBillDataByType(initAlipayPage.UNUSUAL_BILL_RADIO_TYPE)

        else:
            self.showAlipayBillDataByType(initAlipayPage.ALL_BILL_RADIO_TYPE)
            logger.debug("展示所有账单")



    def showAlipayBillDataByType(self, billType):
        '''
        函数功能：展示支付宝账单数据
        :return:
        '''
        logger.debug("call showAlipayBillDataByType function")
        alipayBillAlchemy = AlipayBillAlchemy()

        alipayBillResult = alipayBillAlchemy.SearchAlipayBillByMonthAndType(self.targetDate.year,
                                                                            self.targetDate.month,
                                                                            billType)
        alipayBillLen = len(alipayBillResult)

        self.alipay_bill_tableWidget.setRowCount(alipayBillLen)

        for i in range(alipayBillLen):
            dataRow = alipayBillResult[i]

            noStr = "%d\t" %(i+1)
            noItem = QTableWidgetItem(noStr)
            self.alipay_bill_tableWidget.setItem(i, 0, noItem)


            incomeExpensesItem = QTableWidgetItem(dataRow.income_expenses)
            self.alipay_bill_tableWidget.setItem(i, 1, incomeExpensesItem)



            tradeObjectItem = QTableWidgetItem(dataRow.trade_object)
            self.alipay_bill_tableWidget.setItem(i, 2, tradeObjectItem)


            tradeAccountItem = QTableWidgetItem(dataRow.trade_account)
            self.alipay_bill_tableWidget.setItem(i, 3, tradeAccountItem)



            tradeDescriptionItem = QTableWidgetItem(dataRow.trade_description)
            self.alipay_bill_tableWidget.setItem(i, 4, tradeDescriptionItem)


            receiptPayTypeItem = QTableWidgetItem(dataRow.receipt_pay_type)
            self.alipay_bill_tableWidget.setItem(i, 5, receiptPayTypeItem)


            valueStr = xstring.dispose(toolkit.processValueSignificant(dataRow.value)).humanized_amount(complex=True)
            valueItem = QTableWidgetItem(valueStr)
            self.alipay_bill_tableWidget.setItem(i, 6, valueItem)


            tradeStatusItem = QTableWidgetItem(dataRow.trade_status)
            self.alipay_bill_tableWidget.setItem(i, 7, tradeStatusItem)


            tradeTypeItem = QTableWidgetItem(dataRow.trade_type)
            self.alipay_bill_tableWidget.setItem(i, 8, tradeTypeItem)



            tradeOrderNoItem = QTableWidgetItem(dataRow.trade_order_no)
            self.alipay_bill_tableWidget.setItem(i, 9, tradeOrderNoItem)


            businessOrderNoItem = QTableWidgetItem(dataRow.business_order_no)
            self.alipay_bill_tableWidget.setItem(i, 10, businessOrderNoItem)


            tradeTimeStr = str(dataRow.trade_time)
            tradeTimeItem = QTableWidgetItem(tradeTimeStr)
            self.alipay_bill_tableWidget.setItem(i, 11, tradeTimeItem)


            #针对未匹配记账凭证的账单用橙色背景标注
            if dataRow.bill_type != initAlipayPage.NORMAL_BILL_TYPE:
                noItem.setBackground(initAlipayPage.UNNORMAL_BILL_BACKGROUND_COLOUR)
                incomeExpensesItem.setBackground(initAlipayPage.UNNORMAL_BILL_BACKGROUND_COLOUR)
                tradeObjectItem.setBackground(initAlipayPage.UNNORMAL_BILL_BACKGROUND_COLOUR)
                tradeAccountItem.setBackground(initAlipayPage.UNNORMAL_BILL_BACKGROUND_COLOUR)
                tradeDescriptionItem.setBackground(initAlipayPage.UNNORMAL_BILL_BACKGROUND_COLOUR)
                receiptPayTypeItem.setBackground(initAlipayPage.UNNORMAL_BILL_BACKGROUND_COLOUR)
                valueItem.setBackground(initAlipayPage.UNNORMAL_BILL_BACKGROUND_COLOUR)
                tradeStatusItem.setBackground(initAlipayPage.UNNORMAL_BILL_BACKGROUND_COLOUR)
                tradeTypeItem.setBackground(initAlipayPage.UNNORMAL_BILL_BACKGROUND_COLOUR)
                tradeOrderNoItem.setBackground(initAlipayPage.UNNORMAL_BILL_BACKGROUND_COLOUR)
                businessOrderNoItem.setBackground(initAlipayPage.UNNORMAL_BILL_BACKGROUND_COLOUR)
                tradeTimeItem.setBackground(initAlipayPage.UNNORMAL_BILL_BACKGROUND_COLOUR)

            #现金账单、大额账单中的支出账单用特殊颜色标记
            if ((billType == initAlipayPage.CASH_BILL_RADIO_TYPE or billType == initAlipayPage.LARGE_BILL_RADIO_TYPE) and
                dataRow.income_expenses=="支出"):

                noItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                incomeExpensesItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                tradeObjectItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                tradeAccountItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                tradeDescriptionItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                receiptPayTypeItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                valueItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                tradeStatusItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                tradeTypeItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                tradeOrderNoItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                businessOrderNoItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                tradeTimeItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)

            #花呗账单中超过100的用特殊颜色标记
            if (billType==initAlipayPage.HUA_BEI_BILL_RADIO_TYPE and dataRow.value>initAlipayPage.ALIPAY_BILL_LITTLE_LARGE_VALUE):
                noItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                incomeExpensesItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                tradeObjectItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                tradeAccountItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                tradeDescriptionItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                receiptPayTypeItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                valueItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                tradeStatusItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                tradeTypeItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                tradeOrderNoItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                businessOrderNoItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)
                tradeTimeItem.setBackground(initAlipayPage.MARK_BILL_TEXT_COLOUR)

            '''
            #蚂蚁花呗账单文字用红色展示
            if dataRow.receipt_pay_type!=initAlipayPage.ALIPAY_BILL_HUABEI:
                noItem.setForeground(initAlipayPage.HUABEI_BILL_TEXT_COLOUR)
                incomeExpensesItem.setForeground(initAlipayPage.HUABEI_BILL_TEXT_COLOUR)
                tradeObjectItem.setForeground(initAlipayPage.HUABEI_BILL_TEXT_COLOUR)
                tradeAccountItem.setForeground(initAlipayPage.HUABEI_BILL_TEXT_COLOUR)
                tradeDescriptionItem.setForeground(initAlipayPage.HUABEI_BILL_TEXT_COLOUR)
                receiptPayTypeItem.setForeground(initAlipayPage.HUABEI_BILL_TEXT_COLOUR)
                valueItem.setForeground(initAlipayPage.HUABEI_BILL_TEXT_COLOUR)
                tradeStatusItem.setForeground(initAlipayPage.HUABEI_BILL_TEXT_COLOUR)
                tradeTypeItem.setForeground(initAlipayPage.HUABEI_BILL_TEXT_COLOUR)
                tradeOrderNoItem.setForeground(initAlipayPage.HUABEI_BILL_TEXT_COLOUR)
                businessOrderNoItem.setForeground(initAlipayPage.HUABEI_BILL_TEXT_COLOUR)
                tradeTimeItem.setForeground(initAlipayPage.HUABEI_BILL_TEXT_COLOUR)

            #账单中金额超过200的账单,用粗体标注
            if dataRow.value>initAlipayPage.ALIPAY_BILL_LARGE_VALUE:
                pass
                #noItem.setFont()
            '''

            logger.debug(dataRow.trade_description)

        self.alipay_bill_tableWidget.resizeRowsToContents()  # 设置行宽自适应



    def showErrorMessage(self, errorInfo):
        '''
        函数功能：弹出错误提醒对话框
        :return:
        '''
        logger.debug("call showErrorMessage function")
        QMessageBox.critical(None, "错误", errorInfo, QMessageBox.Ok)

    """
    def onPreviewAlipayVoucherNew(self):
        '''
        函数功能：响应“支付宝记账凭证预览”事件
        :return:
        '''
        logger.debug("call onPreviewAlipayVoucher function")

        self.tabWidget.setCurrentIndex(1)

        autoParseBill = AutoParseBill()
        autoParseBill.alipayBillToAccountVoucher(self.targetDate.year, self.targetDate.month)
        self.showAlipayVoucherPreview()

        QMessageBox.information(None, "提示", "完成预览支付宝记账凭证数据生成", QMessageBox.Ok)

        return True
        
    """
    def onPreviewAlipayVoucher(self):
        '''
        函数功能：响应“支付宝记账凭证预览”事件
        :return:
        '''
        logger.debug("call onPreviewAlipayVoucher function")

        self.tabWidget.setCurrentIndex(1)



        #如果支付宝记账凭证预览表中有数据，对数据进行清空
        accountingVoucherPreview = AlipayVoucherPreviewAlchemy()
        dataCount = accountingVoucherPreview.GetDataCount()
        if (dataCount!=0):
            accountingVoucherPreview.DelAllDataFromTable()


        #判断指定月份的记账凭证是否已经生成
        alipayVoucherAlchemy = AlipayVoucherAlchemy()
        alipayVoucherAlchemyResult = alipayVoucherAlchemy.SearchVoucherByMonth(self.targetDate.year, self.targetDate.month)
        if (len(alipayVoucherAlchemyResult)>0):
            #已经生成了支付宝记账凭证，无法重新生成支付宝记账凭证预览
            QMessageBox.information(None, "【错误】", "当月支付宝记账凭证已经生成，生成支付宝预览记账凭证失败。", QMessageBox.Ok)
            return False

        #####################################################
        #1.0版支付宝账单解析方案
        #####################################################
        ParseAliPay.alipayBillToAccountVoucher(self.targetDate.year, self.targetDate.month)
        #####################################################
        #2.0规则匹配的方式 支付宝账单解析方案
        #####################################################
        #autoParseBill = AutoParseBill()
        #autoParseBill.alipayBillToAccountVoucher(self.targetDate.year, self.targetDate.month)



        self.showAlipayVoucherPreview()

        QMessageBox.information(None, "提示", "完成预览支付宝记账凭证数据生成", QMessageBox.Ok)

        return True

    def onRulePreviewAlipayVoucher(self):
        '''
        函数功能：“规则记账凭证预览”按钮响应函数
        :return:
        '''

        logger.debug("call onRulePreviewAlipayVoucher funciton")
        self.tabWidget.setCurrentIndex(1)

        #这里不应该做删除处理，应该判断是否已经生成了记账凭证预览数据。如果已经生成了，提示进行删除后重新生成
        #如果支付宝记账凭证预览表中有数据，对数据进行清空
        '''
        accountingVoucherPreview = AlipayVoucherPreviewAlchemy()
        dataCount = accountingVoucherPreview.GetDataCount()
        if (dataCount!=0):
            accountingVoucherPreview.DelAllDataFromTable()
        '''

        autoParseBill = AutoParseBill()
        #使用规则解析老的支付宝账单，不再使用
        #autoParseBill.alipayBillToAccountVoucher(self.targetDate.year, self.targetDate.month)

        #使用规则解析新的支付宝账单
        autoParseBill.alipayNewBillToAccountVoucher(self.targetDate.year, self.targetDate.month) #适配更全的支付宝账单
        self.showAlipayVoucherPreview()

        QMessageBox.information(None, "提示", "完成预览支付宝记账凭证数据生成", QMessageBox.Ok)

        return True


    def onClearPreviewAlipayVoucher(self):
        '''
        函数功能：清除指定的预览记账凭证
        :return:
        '''
        logger.debug("call onClearPreviewAlipayVoucher function")
        accountingVoucherPreview = AlipayVoucherPreviewAlchemy()
        accountingVoucherPreview.DelAllDataFromTable()

        #对指定月份的支付宝账单信息的状态进行回退
        alipayBillAlchemy = AlipayBillAlchemy()
        alipayBillAlchemy.TurnbackBillState(self.targetDate.year, self.targetDate.month)

        alipayBillNewAlchemy = AlipayBillNewAlchemy()
        alipayBillNewAlchemy.TurnbackBillState(self.targetDate.year, self.targetDate.month)


    def onGenerateAlipayVoucher(self):
        '''
        函数功能：响应“生成支付宝记账记账凭证”事件
        :return:
        '''

        logger.debug("call onGenerateAlipayVoucher function")

        alipayVoucherPreview = AlipayVoucherPreviewAlchemy()
        startDateStr, endDateStr = toolkit.monthlyChange(self.targetDate.year, self.targetDate.month)
        alipayVoucherResult = alipayVoucherPreview.SearchVoucherByDate(startDateStr, endDateStr)

        alipayVoucherResultLen = len(alipayVoucherResult)

        self.alipay_voucher_tableWidget.setRowCount(alipayVoucherResultLen)


        #将预览记账凭证（支付宝）数据转化为支付宝记账凭证
        for i in range(alipayVoucherResultLen):
            dataRow = alipayVoucherResult[i]
            #AccountVoucherAlchemy
            alipayVoucherAlchemy = AlipayVoucherAlchemy(accountDate=dataRow.account_date,
                                                      voucherNo=dataRow.voucher_no,
                                                      summary=dataRow.summary,
                                                      propertyIncreaseName=dataRow.property_increase_name,
                                                      propertyIncreaseValue=dataRow.property_increase_value,
                                                      propertyDecreaseName=dataRow.property_decrease_name,
                                                      propertyDecreaseValue=dataRow.property_decrease_value,
                                                      ownershipIncreaseName=dataRow.ownership_increase_name,
                                                      ownershipIncreaseValue=dataRow.ownership_increase_value,
                                                      ownershipDecreaseName=dataRow.ownership_decrease_name,
                                                      ownershipDecreaseValue=dataRow.ownership_decrease_value,
                                                      voucherType=dataRow.voucher_type
                                                    )
            # accountingVoucher
            alipayVoucherAlchemy.ShowVoucher()
            alipayVoucherAlchemy.AddVoucherItem()
            #self.AddInvestFlowItem(alipayVoucherAlchemy)

        alipayVoucherPreview = AlipayVoucherPreviewAlchemy()
        dataCount = alipayVoucherPreview.GetDataCount()

        if (dataCount != 0):
            alipayVoucherPreview.DelAllDataFromTable()
            self.initAlipayVoucherPreviewTableUI()
            self.initAlipayVoucherPreviewTableData()

        # 初始化支付宝记账凭证表格
        self.initAlipayVoucherTableUI()
        self.initAlipayVoucherTableData()

        #将支付宝记账凭证归并后，添加入记账凭证总账
        accountVoucherAlchemy = AccountVoucherAlchemy()
        accountVoucherAlchemyResult =accountVoucherAlchemy.SearchVoucherByMonth(self.targetDate.year, self.targetDate.month)

        if (len(accountVoucherAlchemyResult)>0):
            #该月支付宝记账凭证没有合并到总的记账凭证中去，执行合并操作
            QMessageBox.information(None, "【错误】", "记账凭证中已有本月的支付宝记账凭证，合并失败", QMessageBox.Ok)
        else:
            self.pushAlipayVoucherToAccountVoucher(self.targetDate.year, self.targetDate.month)
            QMessageBox.information(None, "提示", "生成支付宝记账凭证", QMessageBox.Ok)

    def onRuleGenerateAlipayVoucher(self):
        '''
        函数功能：按照规则生成记账凭证，
            只做数据复制，合并工作在之前已经完成了。
        :return:
        '''
        pass
        logger.debug("call onRuleGenerateAlipayVoucher funciton")

        alipayVoucherPreview = AlipayVoucherPreviewAlchemy()
        startDateStr, endDateStr = toolkit.monthlyChange(self.targetDate.year, self.targetDate.month)
        alipayVoucherResult = alipayVoucherPreview.SearchVoucherByDate(startDateStr, endDateStr)
        alipayVoucherResultLen = len(alipayVoucherResult)

        for i in range(alipayVoucherResultLen):
            dataRow = alipayVoucherResult[i]
            # AccountVoucherAlchemy
            alipayVoucherAlchemy = AlipayVoucherAlchemy(accountDate=dataRow.account_date,
                                                        voucherNo=dataRow.voucher_no,
                                                        summary=dataRow.summary,
                                                        propertyIncreaseName=dataRow.property_increase_name,
                                                        propertyIncreaseValue=dataRow.property_increase_value,
                                                        propertyDecreaseName=dataRow.property_decrease_name,
                                                        propertyDecreaseValue=dataRow.property_decrease_value,
                                                        ownershipIncreaseName=dataRow.ownership_increase_name,
                                                        ownershipIncreaseValue=dataRow.ownership_increase_value,
                                                        ownershipDecreaseName=dataRow.ownership_decrease_name,
                                                        ownershipDecreaseValue=dataRow.ownership_decrease_value,
                                                        voucherType=dataRow.voucher_type
                                                        )
            # accountingVoucher
            #alipayVoucherAlchemy.ShowVoucher()
            alipayVoucherAlchemy.AddVoucherItem()

            accountVoucher = AccountVoucherAlchemy(accountDate=dataRow.account_date,
                                                        voucherNo=dataRow.voucher_no,
                                                        summary=dataRow.summary,
                                                        propertyIncreaseName=dataRow.property_increase_name,
                                                        propertyIncreaseValue=dataRow.property_increase_value,
                                                        propertyDecreaseName=dataRow.property_decrease_name,
                                                        propertyDecreaseValue=dataRow.property_decrease_value,
                                                        ownershipIncreaseName=dataRow.ownership_increase_name,
                                                        ownershipIncreaseValue=dataRow.ownership_increase_value,
                                                        ownershipDecreaseName=dataRow.ownership_decrease_name,
                                                        ownershipDecreaseValue=dataRow.ownership_decrease_value
                                                        )

            # accountingVoucher.ShowVoucher()
            accountVoucher.AddVoucherItem()
            AddInvestFlowItem(accountVoucher)  # 添加投资数据流记录

        #end for

        alipayVoucherPreview = AlipayVoucherPreviewAlchemy()
        dataCount = alipayVoucherPreview.GetDataCount()

        if (dataCount != 0):
            alipayVoucherPreview.DelAllDataFromTable()
            self.initAlipayVoucherPreviewTableUI()
            self.initAlipayVoucherPreviewTableData()

        # 初始化支付宝记账凭证表格
        self.initAlipayVoucherTableUI()
        self.initAlipayVoucherTableData()


    def onBillItemDoubleClicked(self):
        '''
        函数功能：响应账单表格双击事件，弹出记账凭证解析规则生成对话框
        :return:
        '''

        logger.debug("call onBillItemDoubleClicked function 该函数注释掉暂停使用")
        '''
     
        selectItem = self.alipay_bill_tableWidget.selectedItems()
        selectRow = self.alipay_bill_tableWidget.selectedItems()[0].row()
        selectText = self.alipay_bill_tableWidget.selectedItems()[0].text().strip("\t")


        billParseDialog = BillParseDialog(parent=self, tableHeaderLabels=initAlipayPage.ALIPAY_BILL_COLUMN_CONTEXT, tableKeys=initAlipayPage.ALIPAY_BILL_COLUMN_KEY, selectItem=selectItem)


        if billParseDialog.exec_():
            pass
        billParseDialog.destroy()
        '''

    def onNewBillItemDoubleClicked(self):
        '''
        函数功能：响应账单表格双击事件，弹出记账凭证解析规则生成对话框
        :return:
        '''

        #self.alipay_bill_tableWidget

        selectItem = self.new_alipay_bill_tableWidget.selectedItems()
        selectRow = self.new_alipay_bill_tableWidget.selectedItems()[0].row()
        selectText = self.new_alipay_bill_tableWidget.selectedItems()[0].text().strip("\t")


        billParseDialog = BillParseDialog(parent=self, tableHeaderLabels=initAlipayPage.NEW_ALIPAY_BILL_COLUMN_CONTEXT, tableKeys=initAlipayPage.NEW_ALIPAY_BILL_COLUMN_KEY , selectItem=selectItem)


        if billParseDialog.exec_():
            pass
        billParseDialog.destroy()

    def pushAlipayVoucherToAccountVoucher(self, year, month):
        '''
        函数功能：将支付宝记账凭证数据push到记账凭证总表中。
        :return:
        '''
        logger.debug("call pushAlipayVoucherToAccountVoucher function")

        ParseAliPay.mergeHuabeiAlipayVoucher(year, month)       #合并蚂蚁花呗记账凭证成一条记账凭证
        ParseAliPay.mergeYuebaoEarningsVoucher(year, month)     #合并余额宝记账凭证成一条记账凭证
        ParseAliPay.mergePengHuaBond(year, month)       #合并鹏华基金记账凭证成一条记账凭证
        ParseAliPay.mergeOtherVoucher(year, month)      #将其他支付宝记账凭证合并如记账凭证总表


    def initAlipayBillNewTableUI(self):
        '''
        函数功能：初始化新支付宝账单UI
        :return:
        '''
        logger.debug("call initAlipayBillNewTableUI function")

        self.new_alipay_bill_tableWidget.setRowCount(initAlipayPage.NEW_ALIPAY_BILL_ROW_COUNT)  # 设置行数目
        self.new_alipay_bill_tableWidget.setColumnCount(initAlipayPage.NEW_ALIPAY_BILL_COLUMN_COUNT)  # 设置列数目
        self.new_alipay_bill_tableWidget.setHorizontalHeaderLabels(initAlipayPage.NEW_ALIPAY_BILL_COLUMN_CONTEXT)

        self.new_alipay_bill_tableWidget.resizeRowsToContents()  # 设置行宽自适应
        # self.alipay_bill_tableWidget.resizeColumnsToContents()  # 设置列宽自适应
        self.new_alipay_bill_tableWidget.setShowGrid(True)  # 设置显示网络线
        self.new_alipay_bill_tableWidget.setAlternatingRowColors(True)  # 设置表格颜色交错显示
        self.new_alipay_bill_tableWidget.verticalHeader().setVisible(False)  # 隐藏垂直标题
        self.new_alipay_bill_tableWidget.horizontalHeader().setStretchLastSection(True)  # 设置最后一列自动填充容

        self.new_alipay_bill_tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置选中整行
        self.new_alipay_bill_tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)  # 禁止编辑单元格


        self.new_alipay_bill_tableWidget.setColumnWidth(0, 60)   #序号
        self.new_alipay_bill_tableWidget.setColumnWidth(1, 220)  #交易时间
        self.new_alipay_bill_tableWidget.setColumnWidth(2, 220)     #最近修改时间_B
        self.new_alipay_bill_tableWidget.setColumnWidth(3, 120)     #交易分类
        self.new_alipay_bill_tableWidget.setColumnWidth(4, 150)     #支付类型_B
        self.new_alipay_bill_tableWidget.setColumnWidth(5, 120)     #收支
        self.new_alipay_bill_tableWidget.setColumnWidth(6, 100)     #金额
        self.new_alipay_bill_tableWidget.setColumnWidth(7, 150)     #收/付款方式
        self.new_alipay_bill_tableWidget.setColumnWidth(8, 120)     #交易状态
        self.new_alipay_bill_tableWidget.setColumnWidth(9, 300)     #交易对方
        self.new_alipay_bill_tableWidget.setColumnWidth(10, 350)    #商品说明
        self.new_alipay_bill_tableWidget.setColumnWidth(11, 100)    #备注


    def initAlipayBillNewTableData(self):
        '''
        函数功能：初始化新支付宝账单数据
        :return:
        '''

        logger.debug("call initAliypayBillNewTableData function")
        #self.showAlipayBillData()
        self.showAlipayBillNewDataByType(initAlipayPage.ALL_BILL_RADIO_TYPE)

    def showAlipayBillNewDataByType(self, billType):

        '''
        函数功能：展示支付宝账单数据
        :return:
        AlipayBillNewAlchemy
        '''
        logger.debug("call showAlipayBillNewDataByType function")
        alipayBillNewAlchemy = AlipayBillNewAlchemy()

        alipayBillNewResult = alipayBillNewAlchemy.SearchAlipayBillByMonthAndType(self.targetDate.year,
                                                                            self.targetDate.month,
                                                                            billType)
        alipayBillNewLen = len(alipayBillNewResult)



        self.new_alipay_bill_tableWidget.setRowCount(alipayBillNewLen)


        for i in range(alipayBillNewLen ):
            dataRow = alipayBillNewResult[i]

            noStr = "%d\t" %(i+1)
            noItem = QTableWidgetItem(noStr)
            self.new_alipay_bill_tableWidget.setItem(i, 0, noItem)

            # 交易时间_A
            tradeTimeFirstStr = str(dataRow.trade_time_first)
            tradeTimeFirstItem = QTableWidgetItem(tradeTimeFirstStr)
            self.new_alipay_bill_tableWidget.setItem(i, 1, tradeTimeFirstItem)

            #付款结算时间
            if dataRow.settlement_time!=None:
                settlementTimeStr = datetime.strftime(dataRow.settlement_time, '%Y-%m-%d %H:%M:%S')
            else:
                settlementTimeStr=""
            settlementTimeItem = QTableWidgetItem(settlementTimeStr)
            self.new_alipay_bill_tableWidget.setItem(i, 2, settlementTimeItem)





            # 交易分类_A
            tradeTypeFirstItem = QTableWidgetItem(dataRow.trade_type_first)
            self.new_alipay_bill_tableWidget.setItem(i, 3, tradeTypeFirstItem)

            #类型_B
            typeOtherItem = QTableWidgetItem(dataRow.type_other)
            self.new_alipay_bill_tableWidget.setItem(i, 4, typeOtherItem)



            # 收&支_A
            incomeExpensesFirstItem = QTableWidgetItem(dataRow.income_expenses_first)
            self.new_alipay_bill_tableWidget.setItem(i, 5, incomeExpensesFirstItem)

            # 金额_A
            valueFirstStr = xstring.dispose(toolkit.processValueSignificant(dataRow.value_first)).humanized_amount(complex=True)
            valueFirstItem = QTableWidgetItem(valueFirstStr)
            self.new_alipay_bill_tableWidget.setItem(i, 6, valueFirstItem)

            # 收/付款方式_A
            receiptPayTypeFirstItem = QTableWidgetItem(dataRow.receipt_pay_type_first)
            self.new_alipay_bill_tableWidget.setItem(i, 7, receiptPayTypeFirstItem)

            # 交易状态_B
            tradeStatusOtherItem = QTableWidgetItem(dataRow.trade_status_other)
            self.new_alipay_bill_tableWidget.setItem(i, 8, tradeStatusOtherItem)

            # 交易对方_A
            tradeObjectFirstItem = QTableWidgetItem(dataRow.trade_object_first)
            self.new_alipay_bill_tableWidget.setItem(i, 9, tradeObjectFirstItem)

            # 商品说明_A
            commodityDescriptionFirstItem = QTableWidgetItem(dataRow.commodity_description_first)
            self.new_alipay_bill_tableWidget.setItem(i, 10, commodityDescriptionFirstItem)

            # 备注_A
            remarkFirstItem = QTableWidgetItem(dataRow.remark_first)
            self.new_alipay_bill_tableWidget.setItem(i, 11, remarkFirstItem)


            # 交易订单号_A
            tradeOrderNoFirstItem = QTableWidgetItem(dataRow.trade_order_no_first)
            self.new_alipay_bill_tableWidget.setItem(i, 12, tradeOrderNoFirstItem)

            # 商家订单号_A
            businessOrderNoFirstItem = QTableWidgetItem(dataRow.business_order_no_first)
            self.new_alipay_bill_tableWidget.setItem(i, 13, businessOrderNoFirstItem)

            # 对方账号_A
            tradeAccountFirstItem = QTableWidgetItem(dataRow.trade_account_first)
            self.new_alipay_bill_tableWidget.setItem(i, 14, tradeAccountFirstItem)


            # 交易订单号&交易号_B
            tradeOrderNoOtherItem = QTableWidgetItem(dataRow.trade_order_no_other)
            self.new_alipay_bill_tableWidget.setItem(i, 15, tradeOrderNoOtherItem)

            # 商家订单号_B
            businessOrderNoOtherItem = QTableWidgetItem(dataRow.business_order_no_other)
            self.new_alipay_bill_tableWidget.setItem(i, 16, businessOrderNoOtherItem)

            #交易创建时间strftime_B
            if dataRow.trade_create_time_other!=None:
                tradeCreateTimeOtherStr = datetime.strftime(dataRow.trade_create_time_other, '%Y-%m-%d %H:%M:%S')
            else:
                tradeCreateTimeOtherStr=""
            tradeCreateTimeOtherItem = QTableWidgetItem(tradeCreateTimeOtherStr)
            self.new_alipay_bill_tableWidget.setItem(i, 17, tradeCreateTimeOtherItem)

            #付款时间_B
            if dataRow.trade_payment_time_other!=None:
                tradePaymentTimeOtherStr = datetime.strftime(dataRow.trade_payment_time_other, '%Y-%m-%d %H:%M:%S')
            else:
                tradePaymentTimeOtherStr=""
            tradePaymentTimeOtherItem = QTableWidgetItem(tradePaymentTimeOtherStr)
            self.new_alipay_bill_tableWidget.setItem(i, 18, tradePaymentTimeOtherItem)


            #最近修改时间_B
            if dataRow.trade_last_modified_time_other!=None:
                tradeLastModifiedTimeOtherStr = datetime.strftime(dataRow.trade_last_modified_time_other, '%Y-%m-%d %H:%M:%S')
            else:
                tradeLastModifiedTimeOtherStr=""
            tradeLastModifiedTimeOtherItem = QTableWidgetItem(tradeLastModifiedTimeOtherStr)
            self.new_alipay_bill_tableWidget.setItem(i, 19, tradeLastModifiedTimeOtherItem)



            #交易来源地_B
            tradeSourceOtherItem = QTableWidgetItem(dataRow.trade_source_other)
            self.new_alipay_bill_tableWidget.setItem(i, 20, tradeSourceOtherItem)




            #交易对方_B
            tradeObjectOtherItem = QTableWidgetItem(dataRow.trade_object_other)
            self.new_alipay_bill_tableWidget.setItem(i, 21, tradeObjectOtherItem)

            #商品名称_B
            commodityNameOtherItem = QTableWidgetItem(dataRow.commodity_name_other)
            self.new_alipay_bill_tableWidget.setItem(i, 22, commodityNameOtherItem)

            #金额_B
            valueOtherStr = xstring.dispose(toolkit.processValueSignificant(dataRow.value_other)).humanized_amount(
                complex=True)
            valueOtherItem = QTableWidgetItem(valueOtherStr)
            self.new_alipay_bill_tableWidget.setItem(i, 23, valueOtherItem)

            #收&支_B
            incomeExpensesOtherItem = QTableWidgetItem(dataRow.income_expenses_other)
            self.new_alipay_bill_tableWidget.setItem(i, 24, incomeExpensesOtherItem)

            #交易状态_B
            tradeStatusOtherItem = QTableWidgetItem(dataRow.trade_status_other)
            self.new_alipay_bill_tableWidget.setItem(i, 25, tradeStatusOtherItem)

            #服务费（元）_B
            valueServiceChargeOtherStr = xstring.dispose(toolkit.processValueSignificant(dataRow.value_service_charge_other)).humanized_amount(
                complex=True)
            valueServiceChargeOtherItem = QTableWidgetItem(valueServiceChargeOtherStr)
            self.new_alipay_bill_tableWidget.setItem(i, 26, valueServiceChargeOtherItem)

            #成功退款（元）_B
            valueRefundOtherStr = xstring.dispose(toolkit.processValueSignificant(dataRow.value_refund_other)).humanized_amount(
                complex=True)
            valueRefundOtherItem = QTableWidgetItem(valueRefundOtherStr)
            self.new_alipay_bill_tableWidget.setItem(i, 27, valueRefundOtherItem)

            #备注_B
            remarkOtherItem = QTableWidgetItem(dataRow.remark_other)
            self.new_alipay_bill_tableWidget.setItem(i, 28, remarkOtherItem)

            #资金状态_B
            fundStatusOtherItem= QTableWidgetItem(dataRow.fund_status_other)
            self.new_alipay_bill_tableWidget.setItem(i, 29, fundStatusOtherItem)




            #需要继续添加

            qBrushType=None

            if (dataRow.bill_type != initAlipayPage.NORMAL_BILL_TYPE):
                qBrushType= initAlipayPage.UNNORMAL_BILL_BACKGROUND_COLOUR

            if ((billType == initAlipayPage.CASH_BILL_RADIO_TYPE or billType == initAlipayPage.LARGE_BILL_RADIO_TYPE) and
                dataRow.income_expenses_first=="支出"):
                qBrushType= initAlipayPage.MARK_BILL_TEXT_COLOUR

            if (billType==initAlipayPage.HUA_BEI_BILL_RADIO_TYPE and dataRow.value_first>initAlipayPage.ALIPAY_BILL_LITTLE_LARGE_VALUE):
                qBrushType = initAlipayPage.MARK_BILL_TEXT_COLOUR

            count=range(self.new_alipay_bill_tableWidget.columnCount())

            if qBrushType!=None:
                for col in range(self.new_alipay_bill_tableWidget.columnCount()):
                    item = self.new_alipay_bill_tableWidget.item(i, col)
                    item.setBackground(qBrushType)



        self.alipay_bill_tableWidget.resizeRowsToContents()  # 设置行宽自适应



def  AddInvestFlowItem(accountVoucherItem):
    '''
    函数功能：基于记账凭证数据，添加投资数据流记录
    :param accountVoucherItem:
    :return:
    '''

    #logger.debug("暂缓使用！！！！")

    if (accountVoucherItem.property_increase_value != accountVoucherItem.property_decrease_value):
        # 资产增加值不等于资产减少值，不属于投资行为
        return False


    if (accountVoucherItem.property_increase_name.find("资产->投资->理财") != -1 or \
            accountVoucherItem.property_decrease_name.find("资产->投资->理财") != -1):
        # 资产增加或资产减少项中存在“资产->投资->理财”属性，的记账凭证属于投资行为，可以添加到投资数据流中
        subStringList = accountVoucherItem.property_increase_name.split("->")
        substringListLen = len(subStringList)
        investmentName = subStringList[substringListLen - 1]
        investmentFlowAlchemy = InvestmentFlowAlchemy(investmentDate=accountVoucherItem.account_date,
                                                      investmentValue=accountVoucherItem.property_increase_value,
                                                      investmentPath=accountVoucherItem.property_increase_name,
                                                      flowType=FLOW_TYPE_DING_TOU,
                                                      voucherId=accountVoucherItem.id)

        investmentFlowAlchemy.AddInvestmentItem()


def main():
    alipayBillWidget = AlipayBillWidget()
    alipayBillWidget.mergeHuabeiAlipayVoucher()

if __name__ == '__main__':
    main()

